package com.yupi.springbootinit.manager;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.ThrowUtils;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 限流管理器
 */
@Service
public class RedisLimiterManger {

    @Resource
    private  RedissonClient redissonClient;


    public void doRateLimit(String key){
        // 创建限流器，key为限流器的唯一标识
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        // 设置每秒最大访问次数为3
        rateLimiter.trySetRate(RateType.OVERALL, 3, 1, RateIntervalUnit.SECONDS);
        boolean b = rateLimiter.tryAcquire(1);
        if (!b){
            ThrowUtils.throwIf(true, ErrorCode.TO_MANY_REQUIRE);
        }
    }



}
